package cn.grf.datasource.service;

import cn.grf.datasource.pojo.Account;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author grf
 * @apiNote
 * @since 2025/4/23
 */
@Service
@RequiredArgsConstructor
@Transactional(transactionManager = "secondaryTransactionManager")
public class AccountService {

    @Qualifier("secondaryJdbcTemplate")
    private final JdbcTemplate secondaryJdbcTemplate;

    /**
     * 插入
     * @param account
     */
    public void insert(Account account) {
        var sql = """
            INSERT INTO account (id, name, value, content) VALUES (?, ?, ?, ?)
        """;
        secondaryJdbcTemplate.update(sql, account.getId(), account.getName(), account.getValue(), account.getContent());
    }

    /**
     * 列表
     * @return
     */
    public List<Account> list() {
        String sql = "SELECT * FROM account";
        return secondaryJdbcTemplate.queryForList(sql, Account.class);
    }

    /**
     * 对象查询
     * @param id id
     */
    public Account get(Long id) {
        String sql = "SELECT * FROM account where id = ?";
        return secondaryJdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(Account.class), id);
    }
}
